package com.coincalf.task.task;

import com.coincalf.dto.SmsDTO;
import com.coincalf.feign.SmsServiceClient;
import com.coincalf.framework.enums.CoinWithdrawStatus;
import com.coincalf.framework.enums.SmsTemplate;
import com.coincalf.user.dto.UserDTO;
import com.coincalf.user.feign.UserServiceClient;
import com.coincalf.wallet.feign.CoinWithdrawServiceClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description:
 * @Author: Chen Long
 * @Date: Created in 2018/5/21 下午9:24
 * @Modified by: Chen Long
 */
@Component
@Slf4j
public class CoinWithdrawTask {

    @Autowired
    private CoinWithdrawServiceClient coinWithdrawServiceClient;
    @Autowired
    private SmsServiceClient smsServiceClient;
    @Autowired
    private UserServiceClient userServiceClient;

    /**
     * 提币扣减资金任务，每分钟执行一次
     */
    @Scheduled(fixedRate = 60000)
    public void trigger() {
        coinWithdrawServiceClient.queryPendingRecord().forEach(coinWithdraw -> {
            // 短信通知用户
            UserDTO user = userServiceClient.selectById(coinWithdraw.getUserId());
            Map<String, Object> templateParam = new HashMap<>();
            templateParam.put("amount", coinWithdraw.getMum());
            templateParam.put("coinName", coinWithdraw.getCoinName());
            SmsDTO smsDTO = new SmsDTO();
            smsDTO.setCountryCode(user.getCountryCode())
                    .setMobile(user.getMobile())
                    .setEmail(user.getEmail())
                    .setTemplateCode(SmsTemplate.WITHDRAW_SUCCESS.getCode())
                    .setTemplateParam(templateParam);
            smsServiceClient.sendTo(smsDTO);
            coinWithdraw.setStatus(CoinWithdrawStatus.SUCCESS.getCode());
            coinWithdrawServiceClient.modifyWithdrawStatus(coinWithdraw);
        });
    }

}
